﻿namespace Digitalmes.Application.Sys.Dicts.Commands;

/// <summary>
/// 更新字典数据项命令。
/// </summary>
/// <param name="DictData"></param>
public record UpdateDictItemCommand(SysDictItemDto DictData) : IRequest<IResult<bool>>;

internal sealed class UpdateDictItemCommandHandler(IRepository<SysDictItem> repo) : IRequestHandler<UpdateDictItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateDictItemCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.Label == request.DictData.Label && m.DictId == request.DictData.DictId && m.Id != request.DictData.Id, cancellationToken))
        {
            return Result.Failure("字典标签已存在");
        }

        var dict = request.DictData.Adapt<SysDictItem>();
        var ok = await repo.UpdateAsync(dict, m => new {
            m.Label,
            m.Value,
            m.Order,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
